#include <assert.h>
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  

/*
    Usage:
		gcc main.c
		./a.out encode sample.jpg 137
		./a.out decode sample.jpg.enc 137
*/
  
const int STR_MAX_LEN = 100;  // max length of strings mentioned
const int FNAME_MAX_LEN = 100;  // max permitted length of filename
const char suffix[STR_MAX_LEN] = ".enc";

// utils
   
int getFileSize(char* str) {  
    FILE *f = fopen(str, "rb");  
    fseek(f, 0, SEEK_END);  
    int size =  ftell(f);  
    fclose(f);  
  
    return size;  
}  


int endwith(char* src, char* ending) {
    int srcLen = strlen(src);
    int endingLen = strlen(ending);
    for(int i = 1; i <= endingLen; i++) {
        if(src[srcLen-i] != ending[endingLen-i]) { return 1; }
    }
    return 0;
}


// encrypt and decrypt

void encode(char* srcFname, char* tgtFname, int key) {
    FILE *f1 = fopen(srcFname, "rb");  
    FILE *f2 = fopen(tgtFname, "wb");  
      
    int size = getFileSize(srcFname);  
    for(int i = 0; i < size; i++) { 

        int rand = size + key + i - size / key; // some random thing
        int src = getc(f1);

        // encode logic: rand ^ (rand ^ *) = *
        int tgt = rand ^ src;  
        putc(tgt, f2);  
    }  
  
    fclose(f1);  
    fclose(f2);
}


void encrypt(char* oriFname, int key) {  

    char encryptedFname[FNAME_MAX_LEN];  
    strcpy(encryptedFname, oriFname);  
    strcat(encryptedFname, suffix);
      
    encode(oriFname, encryptedFname, key);  
}  


void decrypt(char* encryptedFname, int key) { 

    assert(endwith(encryptedFname, suffix) == 0);

    char oriFname[FNAME_MAX_LEN]; 
    strcpy(oriFname, encryptedFname);
    oriFname[strlen(encryptedFname) - strlen(suffix)] = 0;  
      
    encode(encryptedFname, oriFname, key);   
}  
  
// main

int main(int argc, char** argv) {  

    char op[STR_MAX_LEN];
    char fname[FNAME_MAX_LEN];
    strcpy(op, argv[1]);
    strcpy(fname, argv[2]);
    int key = atoi(argv[3]);

    if(strcmp(op, "encode") == 0) {
        encrypt(fname, key);
    } else if(strcmp(op, "decode") == 0) {
        decrypt(fname, key);
    } else {
        printf("input format: ./a.out op fname key");
    }

    return 0;  
} 